# -*- coding:utf-8 -*-

from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

SessionLocal = None
Base = declarative_base()
isInit = False
engine = None

async def register_db(dsn="mysql+pymysql://root:123456@127.0.0.1:3306/test", echo=False):
    global isInit, SessionLocal, engine
    if isInit: return
    isInit = True
    
    engine = create_engine(
        dsn, echo=echo, isolation_level="READ COMMITTED"
    )
    SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
    
    # Base.metadata.create_all(bind=engine)

# Dependency
def get_db():
    session = SessionLocal()
    try:
        yield session
        session.commit()
    except:
        session.rollback()
        raise
    finally:
        session.close()